package com.hxl.tech.gateway.auth;


import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import javax.security.auth.x500.X500Principal;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;

/**
 * 证书生成
 */
public class JksGenerator {

    public static void main(String[] args) throws Exception {

        String password = "HXL-OPEN";
        String env = "dev";

        Security.addProvider(new BouncyCastleProvider());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        X509Certificate certificate = generateCertificate(publicKey, privateKey);
        keyStore.setKeyEntry(password, privateKey, password.toCharArray(), new Certificate[]{certificate});

        FileOutputStream fileOutputStream = new FileOutputStream(env+".jks");
        keyStore.store(fileOutputStream, password.toCharArray());
        fileOutputStream.close();
    }

    private static X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey) throws Exception {
        X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
        certGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGenerator.setIssuerDN(new X500Principal("CN=Test Certificate"));
        certGenerator.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24));
        certGenerator.setNotAfter(new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365));
        certGenerator.setSubjectDN(new X500Principal("CN=Test Certificate"));
        certGenerator.setPublicKey(publicKey);
        certGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

        return certGenerator.generate(privateKey);
    }
}


